<template>
  <div>
    <el-table
      v-if="refreshFlag > 0"
      :data="finalSelection"
      style="width: 100%"
      border
      height="800"
      :header-cell-style="{ background: '#eee', color: '#000' }"
    >
      <el-table-column type="index" align="center" label="序号" width="60" />
      <el-table-column prop="macCode" label="加注机编号" min-width="150" />
      <el-table-column label="加注站名称" min-width="180">
        <template v-slot="scope">
          {{ scope.row.siteName | defaultValue }}
        </template>
      </el-table-column>
      <el-table-column label="总容量（吨）" min-width="150">
        <template v-slot="scope">{{
          scope.row.totalCapacity | kg2Tons
        }}</template>
      </el-table-column>
      <el-table-column label="理论剩余容量（吨）" min-width="150">
        <template v-slot="scope">{{
          scope.row.currentCapacity | kg2Tons
        }}</template>
      </el-table-column>
      <el-table-column label="本次补液量（吨）" width="200">
        <template v-slot="scope">
          <div class="flex-center">
            <el-input-number
              :min="0"
              size="small"
              class="m-r-10"
              v-model="finalSelection[scope.$index].expectCapacity"
              :max="finalSelection[scope.$index]._maxCapacity"
              :step="0.01"
              @change="capacityChange"
            />
            <el-button
              circle
              size="mini"
              title="删除"
              type="primary"
              icon="el-icon-minus"
              @click="remove(scope.$index)"
            />
          </div>
        </template>
      </el-table-column>
    </el-table>
    <div class="dividing-line m-t-20 m-b-20"></div>
    <div class="flex-center">
      <div>
        补液总量（吨）<span
          class="m-l-10 f-s-16 f-w-600"
          style="color: #1e9fff"
          >{{ total | defaultValue }}</span
        >
      </div>
      <el-select
        size="small"
        v-model="selectedCar"
        filterable
        remote
        reserve-keyword
        placeholder="请输入补液车牌号"
        :remote-method="getCarList"
        :loading="loading"
      >
        <el-option
          v-for="item in carList"
          :key="item.id"
          :label="item.carNo"
          :value="item.carNo + '-' + item.id"
        >
        </el-option>
      </el-select>
      <el-select
        size="small"
        v-model="selectedUser"
        filterable
        remote
        reserve-keyword
        placeholder="请输入补液员"
        :remote-method="getUserList"
        :loading="loading"
      >
        <el-option
          v-for="item in userList"
          :key="item.id"
          :label="item.realName"
          :value="item.realName + '-' + item.id"
        >
        </el-option>
      </el-select>
      <div class="flex-center">
        <el-button size="small" type="primary" plain @click="hide"
          >取消</el-button
        >
        <el-button
          size="small"
          type="primary"
          @click="doConfirm"
          :loading="loading"
          >确定</el-button
        >
      </div>
    </div>
  </div>
</template>

<script>
import {
  isListEmpty,
  listRemove,
  msgError,
  msgSuccess,
} from "@/util/common-util";
import { save } from "@/api/business/filling-storage-order";
import { getPage as getCars } from "@/api/business/filling-storage-car";
import { getList as getUsers } from "@/api/system/user";

export default {
  name: "rehydration-filling-machine-select-list",
  props: {
    selection: {
      type: Array,
      default: () => [],
    },
  },
  data() {
    return {
      loading: false,
      refreshFlag: 1,
      finalSelection: [],
      total: 0,
      carList: [],
      selectedCar: "",
      selectedUser: "",
      userList: [],
    };
  },
  created() {
    this.finalSelection = this.selection;
    for (const item of this.finalSelection) {
      const v =
        ((Number(item.totalCapacity) - Number(item.currentCapacity)) *
          (100 + Number(item.floatRate))) /
        100;
      item.expectCapacity = Math.floor(((v < 0 ? 0 : v) / 1000) * 100) / 100;
      item._maxCapacity = item.expectCapacity;
    }
    this.capacityChange();
  },
  methods: {
    getCarList(query) {
      if (query !== "") {
        this.loading = true;
        let page = {
          current: 1,
          size: 500,
        };

        getCars(page, { carNo: query }).then((res) => {
          this.loading = false;
          this.carList = res.data.data.records;
        });
      } else {
        this.carList = [];
      }
    },
    getUserList(query) {
      if (query !== "") {
        this.loading = true;
        let page = {
          current: 1,
          size: 500,
        };

        getUsers(page.current, page.size, { realName: query }).then((res) => {
          this.loading = false;
          this.userList = res.data.data.records;
        });
      } else {
        this.userList = [];
      }
    },
    hide(tur) {
      this.$emit("hide");
    },
    remove(_index) {
      listRemove(this.finalSelection, _index);
    },
    capacityChange() {
      this.total = 0;
      for (const item of this.finalSelection) {
        this.total += item.expectCapacity;
      }
      this.refreshFlag = 0;
      this.$nextTick(() => {
        this.refreshFlag = 1;
      });
    },
    doConfirm() {
      const param = [];
      for (const item of this.finalSelection) {
        param.push({
          siteId: item.siteId,
          siteName: item.siteName,
          macCode: item.macCode,
          machineId: item.id,
          expectCapacity: Math.floor(item.expectCapacity * 1000),
        });
      }

      if (isListEmpty(param)) return msgError("请选择加注机");
      console.log(this.selectedCar);
      let form = {
        detailDTOS: param,
        carId: this.selectedCar.split("-")[1],
        userId: this.selectedUser.split("-")[1],
      };
      this.loading = true;
      save(form)
        .then((res) => {
          msgSuccess();
          this.loading = false;
          this.hide();
          this.$emit("finish");
        })
        .catch(() => {
          this.loading = false;
        });
    },
  },
};
</script>

<style lang="scss" scoped></style>
